﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Xml;
using System.Xml.Serialization;
using System.IO;

namespace ScheduleMaker.ConfigManager
{
    public abstract class ConfigManager
    {
        private static XmlSerializer serializer = new XmlSerializer(typeof(Config));
        private static string defaultPath;
        private static Config configuration;
        private static bool configLoaded = false;
        private static bool synchronized = false;

        static ConfigManager()
        {
            String currDir = Directory.GetCurrentDirectory();
            defaultPath = currDir + "\\Config.conf";
        }


        public static bool isConfigLoaded()
        {
            return configLoaded;
        }

        public static bool isSynchronized()
        {
            return synchronized;
        }

        public static bool isConfigFileExists()
        {
            return File.Exists(defaultPath);
        }
        
        public static void loadConfiguration(String path, String password) 
        {
            ConfigFile configFile = new ConfigFile(path, password);
            configFile.Open();
            configuration = (Config)serializer.Deserialize(configFile);
            configLoaded = true;
            synchronized = true;
        }

        public static void saveConfiguration(String path, String password, Config config)
        {
            ConfigFile configFile = new ConfigFile(path, password);
            configFile.createNew();
            //FileStream file = new FileStream(path, FileMode.Create, FileAccess.Write);
            XmlWriterSettings settings = new XmlWriterSettings()
            {
                Encoding = Encoding.UTF8,
                Indent = true,
                NewLineOnAttributes = true,
            };
            using (XmlWriter writer = XmlTextWriter.Create(configFile, settings))
            {
                XmlSerializer tokenSerializer = new XmlSerializer(typeof(Config));
                tokenSerializer.Serialize(writer, config);
            }

            configFile.Save();
            
        }

        public static void loadConfiguration(String password)
        {
            loadConfiguration(defaultPath, password);
        }

        public static void saveConfiguration(String password, Config config)
        {
            saveConfiguration(defaultPath, password, config);
            configuration = config;
            configLoaded = true;
            synchronized = true;
        }

        public static Config getConfiguration()
        {
            return configuration;
        }

        public static void setConfiguration(Config config)
        {
            synchronized = false;
            configLoaded = true;
            configuration = config;
        }
        
    }
}
